import Vue from 'vue'
import Vuex from 'vuex'
import { setItem, getItem, removeItem } from '@/utils/storage'
// import { turn } from 'core-js/fn/array'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    tokenInfo: getItem('tokenInfo') || {},
    // 这个用户基本资料
    userInfo: getItem('userInfo') || {}
  },
  mutations: {
    mUpdateName (state, newName) {
      state.userInfo.name = newName

      setItem('userInfo', state.userInfo)
    },
    mUpdateGender (state, newGender) {
      state.userInfo.gender = newGender

      setItem('userInfo', state.userInfo)
    },
    mUpdateBirthday (state, newBirthday) {
      state.userInfo.birthday = newBirthday
      setItem('userInfo', state.userInfo)
    },
    mUpdatePhoto (state, newPhoto) {
      state.userInfo.photo = newPhoto
      setItem('userInfo', state.userInfo)
    },
    // 这个用户基本资料
    mSetUserInfo (state, userInfo) {
      state.userInfo.birghday = userInfo.birghday
      state.userInfo.geder = userInfo.geder
      state.userInfo.id = userInfo.id.toString()
      state.userInfo.mobile = userInfo.mobile
      state.userInfo.name = userInfo.name
      state.userInfo.photo = userInfo.photo
      // 2.持久化
      setItem('userInfo', state.userInfo)
    },
    // 设置mutation来更新tokenInfo
    mSetTokenInfo (state, tokenObj) {
      // 1.修改token
      state.tokenInfo = tokenObj
      // 2.持久化
      setItem('tokenInfo', tokenObj)
    },
    mClearTokenInfo (state) {
      // 1.保存到vuex
      state.tokenInfo = {}
      // 2.持久化 -- 保存到localstorage
      removeItem('tokenInfo')
    }
  },
  // 它相当于计算属性
  // 基于state中的数据产生新的选项
  // 他是一个函数，会接受state作为参数
  getters: {
    userPhoto (state) {
      return state.userInfo.photo
    },
    isLogin (state) {
      if (state.tokenInfo.token) {
        return true
      }
    }
  }
})
